import ctypes


class RECT(ctypes.Structure):
    # https://learn.microsoft.com/zh-cn/windows/win32/api/windef/ns-windef-rect
    _fields_ = [
        ("left", ctypes.c_long),
        ("top", ctypes.c_long),
        ("right", ctypes.c_long),
        ("bottom", ctypes.c_long),
    ]


# def clip_cursor(p1x=0, p1y=0, p2x=0, p2y=0):
#     if (
#         (not 0 <= p1x <= 9999)
#         or (not 0 <= p1y <= 9999)
#         or (not p1x < p2x <= 9999)
#         or (not p1x < p2y <= 9999)
#     ):
#         err = ctypes.windll.user32.ClipCursor(0)
#         return False

#     rect = RECT()
#     rect.left = p1x
#     rect.top = p1y
#     rect.right = p2x
#     rect.bottom = p2y
#     err = ctypes.windll.user32.ClipCursor(rect)
#     if err:
#         return False
#     else:
#         return True

#      0：理论最小左上角
#     -8：实际最小左上角（受window系统窗口边框？阴影？影响）
#   9900：理论最大左上角（预留99给宽高做减法）
def clip_cursor_wh(x=0, y=0, w=0, h=0):
    if (
        (not -8 <= x <= 9900)
        or (not -8 <= y <= 9900)
        or (not 0 < w <= 9999 - x)
        or (not 0 < h <= 9999 - y)
    ):
        err = ctypes.windll.user32.ClipCursor(0)
        return False

    rect = RECT()
    rect.left = x
    rect.top = y
    rect.right = x + w
    rect.bottom = y + h
    err = ctypes.windll.user32.ClipCursor(rect)
    if err:
        return False
    else:
        return True
